package com.example.inboxdemo.component;

import com.example.inboxdemo.pojo.entity.PublishDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.listener.MessageListener;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;

/**
 * 订阅用户消息
 *
 * @author hongqianli@dobest.com
 * @since 2022/3/25 下午5:44
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class InboxUserTopicListener implements MessageListener<PublishDTO> {

    @Override
    public void onMessage(CharSequence channel, PublishDTO msg) {
        String target = msg.getTarget();
        // 如果目标发送用户存在于当前实例
        if (SseEmitterServer.onlineUserEmitters.containsKey(target)) {
            SseEmitter emitter = SseEmitterServer.onlineUserEmitters.get(target);
            try {
                emitter.send(msg);
            } catch (Exception e) {
                log.info("发送站内信失败：{}，用户可能已下线", target);
            }
        }
    }
}
